<template>
	<div>
		<el-form :model="formData" label-width="120px" :rules="rules" ref="payrollRealityFormAddRef">
			<el-form-item label="项目名称">
				<el-input v-model="project.ProjectName" disabled></el-input>
			</el-form-item>
			<el-row>
				<el-col :span="6">
					<el-form-item label="施工类别" prop="constructionType">
						<el-select v-model="formData.constructionType" style="width: 100%;">
							<el-option v-for="(item,index) in $parent.$parent.constructionType" :value="item.Value"
								:label="item.Description"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="施工部位" prop="constructionPart">
						<el-select v-model="formData.constructionPart" style="width: 100%;">
							<el-option v-for="(item,index) in $parent.$parent.constructionPart" :value="item.Value"
								:label="item.Description"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="工作内容" prop="jobContent">
						<el-select v-model="formData.jobContent" style="width: 100%;">
							<el-option v-for="(item,index) in $parent.$parent.payrollFormConstructionType"
								:value="item.Value" :label="item.Description"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="责任人" prop="personId">
						<el-select v-model="formData.personId" style="width: 100%;">
							<el-option v-for="(item,index) in $store.state.AllUsers" :value="item.Id"
								:label="item.UserName" v-if="item.RoleId != '1'"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="6">
					<el-form-item label="方量(平方数量)" prop="squarequantity">
						<el-input v-model="formData.squarequantity" @blur="gettotalPrice"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="单价" prop="price">
						<el-input v-model="formData.price" @blur="gettotalPrice"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="总价" prop="totalprice">
						<el-input disabled v-model="formData.totalprice"></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="24">
					<el-popover
					  placement="right"
					  width="400"
					  trigger="click">
					  <el-table :data="projectUserList" @select="selectionLineChangeHandle" @select-all="selectionLineChangeHandle"  ref="projectUserListRef">
						<el-table-column type="selection" width="42" align="center"></el-table-column>
					    <el-table-column width="100" property="UserName" label="姓名" align="center"></el-table-column>
						<el-table-column header-align="center" prop="UserNumber" label="工号" align="center"></el-table-column>
						<el-table-column header-align="center" prop="Phone" label="联系电话" align="center" width="150"></el-table-column>
					  </el-table>
					 <el-button type="primary" icon="el-icon-plus" slot="reference" size="mini">添加人员</el-button>
					</el-popover>
					<el-table :data="formData.users" style="width: 100%;" ref="multipleTable" :cell-style="{ padding: '5px 0 ' }">
						<el-table-column header-align="center" fixed prop="id" label="姓名" align="center">
							<template slot-scope="scope">
								{{ getUserInfo(scope.row,'UserName') }}
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="UserNumber" label="工号" align="center">
							<template slot-scope="scope">
								{{ getUserInfo(scope.row,'UserNumber') }}
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="jobCreateTime" label="工作开始时间" align="center">
							<template slot-scope="scope">
								 <el-date-picker v-if="scope.row.isupdata" @blur="TimeChange(scope.row)"
								      v-model="scope.row.jobCreateTime"  format="yyyy - MM - dd"
								      type="date"
								      placeholder="选择日期">
								    </el-date-picker>
								<p v-else>{{ timeForMat(scope.row.jobCreateTime) }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="jobCreateTime" label="工作结束时间" align="center">
							<template slot-scope="scope">
								 <el-date-picker v-if="scope.row.isupdata" @blur="TimeChange(scope.row)"
								      v-model="scope.row.jobEndTime" format="yyyy - MM - dd"
								      type="date"
								      placeholder="选择日期">
								    </el-date-picker>
								<p v-else>{{ timeForMat(scope.row.jobEndTime) }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="jobContent" label="工作内容" align="center">
							<template slot-scope="scope">
								<el-input v-model="scope.row.jobContent" v-if="scope.row.isupdata"></el-input>
								<p v-else>{{ scope.row.jobContent }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="workingDays" label="工天" align="center">
<!-- 							<template slot-scope="scope">
								<el-input v-model.number="scope.row.workingDays" v-if="scope.row.isupdata"></el-input>
								<p v-else>{{ scope.row.workingDays }}</p>
							</template> -->
						</el-table-column>
						<el-table-column header-align="center" prop="price" label="单价" align="center">
							<template slot-scope="scope">
								<el-input v-model.number="scope.row.price" v-if="scope.row.isupdata"></el-input>
								<p v-else>{{ scope.row.price }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="UserNumber" align="center" label="操作">
							<template slot-scope="scope">
								<!-- <el-button type="text" plain size="mini" @click="tableHandler(scope.row,'updata')">{{ scope.row.isupdata?'完成':'编辑' }}</el-button> -->
								<el-button type="text" plain size="mini" style="color: #F56C6C;" @click="tableHandler(scope.row,'delete')">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="24" align="right">
					<el-button type="primary" @click="addPayrollFormHandler()">保存</el-button>
				</el-col>
			</el-row>
		</el-form>
	</div>
</template>

<script>
	import dayjs from 'dayjs'
	import { CheckAmount } from "../../../../public/Scriput/Public.js"
		
	export default {
		name:'payrollRealityFormAdd',
		props: {
			project: {
				type: Object,
				required: false
			},
			closeFun: {
				type: Function,
				reuqired: false,
			},
			jobContentList:{
				type: Array,
				required: false
			}
		},
		data() {
			var squarequantityRule = (rule, value, callback) =>{
				if(value == '') callback(new Error('请输入方量(平方数量)'))
				else if(!CheckAmount(value)) callback(new Error('请填写有效的方量数额(保留两位小数)'))
				else callback()
			};
			var priceRule = (rule, value, callback) =>{
				if(value == '') callback(new Error('请输入方量单价'))
				else if(!CheckAmount(value)) callback(new Error('请填写有效的方量单价(保留两位小数)'))
				else callback()
			};	
			return {
				formData: {
					projectId: 0,
					payrollNumber: "",
					payrollFormType:2,
					constructionType: '',
					constructionPart: '',
					jobContent: '',
					squarequantity: 0,
					price: 0,
					personId: '',
					totalprice: 0,
					remarks: "",
					createTime: dayjs(Date()).format('YYYY-MM-DD hh:mm:ss'), 
					payrollFormType:2,
					users: []
				},
				projectUserList:[],
				selectEdUserList:[],
				rules:{
					constructionType:[ { trigger:'change',message:'请选择施工类别',required:true } ],
					constructionPart:[ { trigger:'change',message:'请选择施工部位',required:true } ],
					jobContent:[ { trigger:'change',message:'请选择工作内容',required:true } ],
					personId:[ { trigger:'change',message:'请选择责任人',required:true } ],
					squarequantity:[{ trigger:'blur',validator:squarequantityRule }],
					price:[{ trigger:'blur',validator:priceRule }]	
				},
			}
		},
		computed:{
			gettotalPrice(){
				const { squarequantity,price }  = this.formData || 0
				let result = squarequantity * price
				if(isNaN(result)){
					this.formData.totalprice = 0
				} else{
					this.formData.totalprice = result.toFixed(2)
				}	
			}
		},
		created() {
			this.formData.projectId = this.project.Id
			this.getPorjectUsers()
		},
		mounted() {
			
		},
		methods: {
			addPayrollFormHandler() {
				let _this = this
				this.$refs.payrollRealityFormAddRef.validate((valid)=>{
					if(valid){
						this.$http.post('PayrollForm/AddPayrollForm',{ payroll:{ ...this.formData },users: this.formData.users  }).then(res => {
							const { StatusCode,Data } = res.data || 0
							if(StatusCode == 200){
								this.$message.success('添加成功')
								this.closeFun()
								this.clearFormData()
							} 
						})						
					}
				})
			},
			//清空表单数据
			clearFormData(){
				this.$refs.payrollRealityFormAddRef.resetFields()
				this.$refs.projectUserListRef.clearSelection()
				this.formData.users = []
			},
			//获取项目下的人员
			getPorjectUsers(){
				this.projectUserList = []
				let { UserIds } = this.project || ''
				let ids = UserIds.split(',')
				ids.forEach(x=>{
					let user = this.$store.state.AllUsers.find(u=>u.Id == x) || undefined
					if(user != undefined) this.projectUserList.push(user)
				})
			},
			//表格选中
			selectionLineChangeHandle(value){
				let newvalue = [...value]
				value.forEach((x,index)=>{
					const { Id } = value || 0
					let U_index = this.selectEdUserList.findIndex(u=>u.Id == Id)
					if(U_index >= 0) newvalue[index] = this.selectEdUserList[U_index]
				})
				this.selectEdUserList = newvalue
				
				this.formData.users = this.selectEdUserList.map(x=>{
					return {
						id: 0,
						delete: false,
						operatId: 0,
						operatDate: "",
						formId: 0,
						projectId: this.project.Id,
						userId: x.Id,
						jobContent: "",
						workingDays: 0,
						price: 0,
						remarks: "",
						payrollType: 0,
						formType: 0,
						jobCreateTime:'',
						jobEndTime:'', 
						isupdata:true,
					}
				})
				
			},
			//获取用户的信息
			getUserInfo(row,type){
				let user = this.$store.state.AllUsers.find(u=>u.Id == row.userId) || undefined
				return user[type]
			},
			//表格操作
			tableHandler(row,type){
				let index = this.formData.users.findIndex(x=>x.userId == row.userId)
				if(type == "updata"){
					this.formData.users[index].isupdata = !this.formData.users[index].isupdata
				}else{
					this.formData.users.splice(index,1)	
				}
				this.$refs.projectUserListRef.clearSelection()
				this.formData.users.forEach(x=>{
					let user = this.projectUserList.find(p=>p.Id == x.userId)
					if(user!=undefined) {
						this.$nextTick(()=>{
							this.$refs.projectUserListRef.toggleRowSelection(user)
						})
					}
				})
			},
			//时间选择
			TimeChange(row){
				const { jobCreateTime,jobEndTime,userId } = row || ''
				if(jobCreateTime!='' && jobEndTime!='' ){
					row.workingDays = (dayjs(jobEndTime).diff(jobCreateTime,'day')) + 1 
					this.$http.post('PayrollForm/UserByProjectDate',{
						userId: userId,
						jobStartDate: jobCreateTime,
						jobEndDate: jobEndTime,
						formType: 2,
					}).then(res=>{
						const { Message,Status } = res.data || 0
						if(!Status) {
							this.$message.warning(Message)
							row.jobCreateTime = '' 
							row.jobEndTime = '' 
						}
					})
				}
			},
			timeForMat(time){
				if(time!='') return dayjs(time).format('YYYY-MM-DD')
				else return ''
			}
		},
	}
</script>

<style scoped>
</style>